<?php
include_once "../config/config.php"; 
//require_once dirname(__FILE__).'/AdminOnlyPageHeader.php';

	$page =  isset($_GET['page']) ? $_GET['page'] : 0; // get the requested page
	$limit = isset($_GET['rows']) ? $_GET['rows'] : 1; // get how many rows we want to have into the grid
	$sidx = isset($_GET['sidx']) ? $_GET['sidx'] : ''; // get index row - i.e. user click to sort
	$sord = isset($_GET['sord']) ? $_GET['sord'] : ''; // get the direction

if(!$sidx) $sidx = 1;

$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : ''; 
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: '';  
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : '';

/*
$myFile = "C:\\Gedimino\\temp2\\testFile1.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "q=".$_GET["q"]."\n";
fwrite($fh, $stringData);
$stringData = "00 page={$page} limit={$limit} sidx={$sidx} sord={$sord}\n";
fwrite($fh, $stringData);
$stringData = "01 searchField={$searchField} searchOper={$searchOper} searchString={$searchString}\n";
fwrite($fh, $stringData);
fclose($fh);
*/

$tblNames = array("1" => "uzduotis_create", 
			      "2" => "uzduotis_select",
				  "3" => "uzduotis_insert",
				  "4" => "uzduotis_update",
				  "5" => "uzduotis_delete");
/*
$myFile = "C:\\Gedimino\\temp2\\testFile2.txt";
$fh = fopen($myFile, 'w') or die("can't open file");		
foreach ($tblNames as $key => $value) {
	$stringData = "01 {$key}=>{$value}\n";
	fwrite($fh, $stringData);
}
fclose($fh);
*/
switch ($_GET["q"]) {
	case "1":
		$whereCond = GetThemeWhereCondition($searchField, $searchOper, $searchString);
		$orderBy = GetThemeOrderBy($sidx, $sord);
		echo TitleGrid($whereCond, $orderBy);	
		break;
	case "2":
		echo TaskGrid();	
		break;
	case "3":
		echo PostTaskTemaUpdate();	
		break;
	case "4":
		echo PostTaskDetailInsert();	
		break;
}
exit();

function TitleGrid($whereCond, $orderBy) {
	global $workDB;

	$query = "SELECT * from temupavadinimai {$whereCond} {$orderBy}";

	$result = mysql_query($query, $workDB);	 
    $i = 0;
    $tasks = array();
    while ($row = mysql_fetch_assoc($result)) {
         $tasks[$i] = $row;
         $i ++;  
    }	
	$xmlRsp = "<?xml version='1.0' encoding='utf-8'?>";
	$xmlRsp .= "<rows>";
	$xmlRsp .=    "<page>1</page>";
	$xmlRsp .=    "<total>".count($tasks)."</total>";
	$xmlRsp .=    "<records>".count($tasks)."</records>";
	
	foreach ($tasks as $key=>$value)
	{
	    $xmlRsp .= "<row id='".$value['id']."'>";
	    $xmlRsp .=    "<cell>".$value['id']."</cell>";
	    $xmlRsp .=    "<cell><![CDATA[".$value['Tema']."]]></cell>";
	    $xmlRsp .= "</row>";
	}
	
	$xmlRsp .=  "</rows>";
	return $xmlRsp;
}

function TaskGrid()
{
	global $tblNames;		
	global $page;		
	global $limit; // get how many rows we want to have into the grid
	global $sidx;  // get index row - i.e. user click to sort
	global $sord;		
	global $searchField; 
	global $searchOper;
	global $searchString;
	$id = $_GET["id"];

	$currentTbl = $tblNames[$id];
	if ($sidx != "1") {
		$sidx = $currentTbl.".".$sidx;	
	}
/*
$myFile = "C:\\Gedimino\\temp2\\testFile1.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = serialize($tblNames);
fwrite($fh, $stringData);
$stringData = "0 - id={$id} currentTbl={$currentTbl}\n";
fwrite($fh, $stringData);
$stringData = "1 - limit={$limit} page={$page} sidx={$sidx} sord={$sord}\n";
fwrite($fh, $stringData);
$stringData = "2 - searchField={$searchField} searchOper={$searchOper} searchString={$searchString}\n";
fwrite($fh, $stringData);
fclose($fh);
*/
	$objRsp = FetchAllTasks($currentTbl, $limit, $page, $sidx, $sord, $searchField, $searchOper, $searchString);

	$xmlRsp = "<?xml version='1.0' encoding='utf-8'?>";
	$xmlRsp .= "<rows>";
	$xmlRsp .=    "<page>".$objRsp->page."</page>";
	$xmlRsp .=    "<total>".$objRsp->total."</total>";
	$xmlRsp .=    "<records>".$objRsp->records."</records>";
	// Funkcija escapeString($str)  panaikina blogus simbolius. Funkcija yra config.php faile
	if ($objRsp->records > 0)
	{
		foreach ($objRsp->rows as $row)
		{
		    $xmlRsp .= "<row id='". $row["id"]."'>";
		    $xmlRsp .=    "<cell>".$row['id']."</cell>";
		    $xmlRsp .=    "<cell><![CDATA[".escapeString($row['task'])."]]></cell>";
		    $xmlRsp .=    "<cell><![CDATA[".escapeString($row['command'])."]]></cell>";
		    $xmlRsp .=    "<cell><![CDATA[".escapeString($row['tbl'])."]]></cell>";
		    $xmlRsp .= "</row>";
		}
	}
	$xmlRsp .=  "</rows>";
/*
$myFile = "C:\\Gedimino\\temp2\\testFile.xml";
$fh = fopen($myFile, 'w') or die("can't open file");		
fwrite($fh, $xmlRsp);
fclose($fh);
*/
	return $xmlRsp;		
}

function PostTaskTemaUpdate()
{
	$data = new stdClass();
	$data->operation = isset($_POST['mode']) ? $_POST['mode'] : '';
	$data->id = isset($_POST['rcId']) ? $_POST['rcId'] : '';
	$data->tema = isset($_POST['Tema']) ? $_POST['Tema'] : '';
/*
$myFile = "C:\\Gedimino\\temp2\\testFile3.xml";
$fh = fopen($myFile, 'w') or die("can't open file");		
$stringData = "operation={$data->operation} id={$data->id} tema={$data->tema}\n";
fwrite($fh, $stringData);
fclose($fh);
*/
	$rsp = UpdateTasksData($data);
	$s1 = strlen($rsp) < 1 ? "OK" : "Error";

	$result = array("operation" => $data->operation, "status" => $s1, "errorMsg" => $rsp,
		"rcId" => $data->id,
	    "Tema" => $data->tema
	);
	return json_encode($result);
}

function PostTaskDetailInsert()
{
	global $tblNames;

	$data = GetPostedDetailData();
	$data->errorMessage = ValidateData($data);

	if (!$data->errorMessage)
	{
		switch($data->operation)
		{
			case "insert":
				if ($tblNames[$data->rootRecordId] == 'uzduotis_create')
					$data->currentRecordId = InsertUzduotisCreate($data);
				else
					$data->currentRecordId = InsertKitosLentos($data, $tblNames[$data->rootRecordId]);
				if ($data->currentRecordId < 0)
					$data->errorMessage = 'Duomenų bazės klaida įterpiant užrašą.';
				break;
			case "edit":
				if ($tblNames[$data->rootRecordId] == 'uzduotis_create')
					$errorInd = UpdateUzduotisCreate($data);
				else
					$errorInd = UpdateKitosLentos($data, $tblNames[$data->rootRecordId]);
				if ($errorInd < 0)
					$data->errorMessage = 'Duomenų bazės klaida įterpiant užrašą.';
				break;
			case "delete":
				if ($tblNames[$data->rootRecordId] == 'uzduotis_create')
					$errorInd = DeleteUzduotisCreate($data);
				else
					$errorInd = DeleteKitosLentos($data, $tblNames[$data->rootRecordId]);
				if ($errorInd < 0)
					$data->errorMessage = 'Duomenų bazės klaida įterpiant užrašą.';
				break;
		}
	}
	$data->status = $data->errorMessage ? 'Error' : 'OK';
	$rzlt = json_encode($data);
/*
$myFile = "C:\\Gedimino\\temp2\\testFile3.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = serialize($data);
fwrite($fh, $stringData);
fwrite($fh, $rzlt);
fclose($fh);
*/
	return $rzlt;
}



function GetThemeWhereCondition($searchField, $searchOper, $searchString)
{
    if (!$searchField || !$searchOper || $searchField != 'Tema')  //Šie laukai yra būtini paieškai
        return '';

    switch ($searchOper)
    {
        case 'eq':
            return "WHERE {$searchField} = '{$searchString}'";
        case 'ne':
            return "WHERE {$searchField} <> '{$searchString}'";
        case 'bw':
            return "WHERE {$searchField} LIKE '{$searchString}%'";
        case 'bn':
            return "WHERE {$searchField} NOT LIKE '{$searchString}%'";
        case 'in':
            return "WHERE {$searchField} LIKE '%{$searchString}%'";
        case 'ni':
            return "WHERE {$searchField} NOT LIKE '%{$searchString}%'";
        case 'ew':
            return "WHERE {$searchField} LIKE '%{$searchString}'";
        case 'en':
            return "WHERE {$searchField} NOT LIKE '%{$searchString}'";
        default:
            return '';
    }
}
function GetThemeOrderBy($sidx, $sord)
{
    if ($sidx != 'Tema' || !$sord)  //Šie laukai yra būtini rūšiavimui
        return '';
    else 
    	return "ORDER BY {$sidx} {$sord}";
}

function GetPostedDetailData()
{
	$data = new stdClass();
	$data->tableId = isset($_POST['tableId']) ? $_POST['tableId'] : '';
	$data->operation = isset($_POST['mode']) ? $_POST['mode'] : '';
	$data->rootRecordId = isset($_POST['rootRecordId']) ? $_POST['rootRecordId'] : '';
	$data->currentRecordId = isset($_POST['currentRecordId']) ? $_POST['currentRecordId'] : '';
	$data->taskDescription = isset($_POST['taskDescription']) ? $_POST['taskDescription'] : '';
	$data->sqlDefinition = isset($_POST['sqlDefinition']) ? $_POST['sqlDefinition'] : '';
	$data->selectedTable = isset($_POST['selectedTable']) ? $_POST['selectedTable'] : '';

	return $data;
}

function ValidateData($data)
{
    global  $tblNames;

	// Šios klaidos gali kilti tik dėl programavimo klaidos
	if (!$data->tableId)
		return "Programos klaida: nenurodytas kintamasis 'tableId'";
	if (!$data->operation)
		return "Programos klaida: nenurodytas kintamasis 'mode'";
	if (strlen($data->rootRecordId) < 1)
		return "Programos klaida: nenurodytas kintamasis 'rootRecordId'";
	if (strlen($data->currentRecordId) < 1)
		return "Programos klaida: nenurodytas kintamasis 'currentRecordId'";
	if (!isset($tblNames[$data->rootRecordId]))
		return "Programos klaida: pagrindinio užrašo indeksas 'rootRecordId'";

	// Vartotojo klaidos (turėtų būti pagauta JavaSkripte)
	if (!$data->taskDescription)
		return "Neužpildyta užduotis (laukas 'taskDescription')";
	if ($tblNames[$data->rootRecordId] != 'uzduotis_create')
	{
		if (!$data->sqlDefinition)
			return "Neužpildyta sql sakinys (laukas 'sqlDefinition')";
	}

	return '';		// Klaidų nėra
}
?>